package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.TravelComment;
import cn.wolfcode.wolf2w.query.TravelCommentQuery;
import cn.wolfcode.wolf2w.repository.TravelCommentRepository;
import cn.wolfcode.wolf2w.service.ITravelCommentService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;


@Service
//@Transactional mongodb事务必须是复制集方式
public class TravelCommentServiceImpl implements ITravelCommentService{


    @Autowired
    private TravelCommentRepository repository;


    @Autowired
    private MongoTemplate template;

    @Override
    public void save(TravelComment travelComment) {
        travelComment.setId(null);
        travelComment.setCreateTime(new Date());

        //关联的评论
        String refId = travelComment.getRefComment().getId();

        if (StringUtils.hasLength(refId)){
            //回复评论
            TravelComment refcomment = this.get(refId);
            travelComment.setRefComment(refcomment);

            travelComment.setType(TravelComment.TRAVLE_COMMENT_TYPE_COMMENT);
        }else {
            travelComment.setType(TravelComment.TRAVLE_COMMENT_TYPE);
        }
        repository.save(travelComment);
    }

    @Override
    public void update(TravelComment travelComment) {
        repository.save(travelComment);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public TravelComment get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<TravelComment> list() {
        return repository.findAll();
    }

    @Override
    public Page<TravelComment> query(TravelCommentQuery qo) {
        //查询对象
        Query query = new Query();

        if(StringUtils.hasLength(qo.getTravelId())){
            query.addCriteria(Criteria.where("strategyId").is(qo.getTravelId()));
        }


        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.DESC,"createTime");
        return DBHelper.query(template,TravelComment.class,query,pageable);
    }

    @Override
    public List<TravelComment> queryByTravelId(String travelId) {
        return repository.findByTravelId(travelId);
    }


}
